import { Component } from '@angular/core';
import {ICellEditorAngularComp} from '@ag-grid-community/angular';
import { Constants } from '../../../utils/constants';
import {FormGroup} from "@angular/forms";

@Component({
  selector: 'apes-cell-editor-details',
  template: `
       <div apes-row [apesGutter]="8" style="width:500px;height: 300px">
         <formly-form [model]="model" [fields]="fields"   [form]="form"></formly-form>
       </div>
     `,
  styles: []
})
export class EditorDetailsComponent implements ICellEditorAngularComp {
  inputValue: any;
  params: any;
  model={};
  fields:any;
  form:any;

  constructor() {
  }

  agInit(params: any): void {
    this.params = params;
    this.model = params.value;
    this.form = new FormGroup({});
    this.fields = [{
      key: 'email',
      type: 'input',
      col: 24,
      lblCol: 16,
      templateOptions: {
        label: 'Email',
        placeholder: 'Enter email',
        required: true,
      }
    },
      {
      key: 'address',
      type: 'input',
      col: 24,
      lblCol: 16,
      templateOptions: {
        label: 'address',
        placeholder: 'Enter email',
        required: true,
      }
    }];
  }

  ngAfterViewInit() {

  }
  isPopup(): boolean {
    return true;
  }

  getValue(): any {
    let result;
    if (!this.form.value) {
      result = '';
      this.params.value = '';
    } else {
      result = this.form.value;
      this.params.value = this.form.value;
    }
    return result;
  }

  onKeyDown(event): void {
    let key = event.which || event.keyCode;
    if (key === 38 || key === 40) {
      this.preventDefaultAndPropagation(event);
    }else if (key == 13 || key == 9) {
      this.inputValue = event.target.value;
      this.params.value = event.target.value;
    }
    if (key == Constants.KEY_LEFT ||
      key == Constants.KEY_UP ||
      key == Constants.KEY_RIGHT ||
      key == Constants.KEY_DOWN ||
      (event.shiftKey && key == Constants.KEY_ENTER)) { // shift+enter allows for newlines
      event.stopPropagation();
    }
  }

  private preventDefaultAndPropagation(event) {
    event.preventDefault();
    event.stopPropagation();
  }
}
